#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
import httplib2

class Tester():
	parser = None
	List = None
	
	def __init__(self,parser):
		self.parser = parser
		print ("Init...")
		
	def DrawTitle(self, text):
		print("-----------------------------")
		print(text)
		print("-----------------------------")
	
	def DataTest(self):
		
		error = 0
		
		if (self.parser == 1):
			try:
				self.DrawTitle("Rutor parsing")
				self.List = ParserRutor()
				self.List.printAllItems()
			except:
				self.DrawTitle("Error in parser")
				error = 2
			
		if (self.parser == 3):
			try:
				self.DrawTitle("Torrentino parsing")
				self.List = ParserTorrentino()
				self.List.printAllItems()
			except:
				self.DrawTitle("Error in parser")
				error = 2
				
		if (self.parser == 2):
			try:
				self.DrawTitle("OpenSharing parsing")
				self.List = ParserOpenSharing()
				self.List.printAllItems()
			except:
				self.DrawTitle("Error in parser")
				error = 2
			
		if (error == 0):
			self.DrawTitle("Start data test")
			
			for item in self.List.GetArrayList():
				if (item.title == None) or (item.title == ""):
					print("Error parsing title in item: %s" % item)
					error = 1
				if (item.link == None) or (item.link == ""):
					print("Error parsing link in item: %s" % item)
					error = 1
				if (item.size == None) or (item.size == ""):
					print("Error parsing size in item: %s" % item)
					error = 1
				if (item.seeds == None) or (item.seeds == ""):
					print("Error parsing seeds in item: %s" % item)
					error = 1
		
			
		if error > 0:
			self.DrawTitle("Occured Errors!!!")
		else:
			self.DrawTitle("Test complete")
				
class Entry():
	title 	= None
	link 	= None
	seeds 	= None
	size 	= None
	
	def __init__(self, sTitle = None, sLink = None, sSeeds = None, sSize = None):
		self.title = sTitle
		self.link = sLink
		self.seeds = sSeeds
		self.size = sSize
	
class EntryList():
	ListOfItems = 0
	
	def __init__(self):
		self.ListOfItems = []
		
	def addItem(self, entry):
		self.ListOfItems.append(entry)
		
	def printAllItems(self):
		for entry in self.ListOfItems:
			print("Title: %s" % entry.title)
			print("Link:  %s" % entry.link)
			print("Seeds: %s" % entry.seeds)
			print("Size:  %s" % entry.size)
			print("------------------------------")
			
	def GetArrayList(self):
		return self.ListOfItems


#////////////////////////////////////////////////////////////////////////////////
### HELPER'S
def PrepareTitle(text):
	
	newString = ""
	
	for item in text:
		newString = newString + item.string
		
	return text


#///////////////////////////////////////////////////////////////////////////////
### TORRENTINO PARSER
def ParserTorrentino():
	
	List = EntryList()
	
	h = httplib2.Http()
	response, content = h.request(('http://www.torrentino.com/search?search=call').replace(' ', '+'))
	html_file = content
	
	soup = BeautifulSoup(html_file)
	rang = soup.find("div", { "class": "results"})
	count = int(len(rang.findAll("li")))
	
	i = 0 
	
	while i < count-14:
		rows = rang.findAll("li")[i]
		
		entry = Entry()
		
		hh = rows.findAll("h4", {"class" : "h4 col1" })
		entry.title = hh[0].contents[1].string
		entry.link = hh[0].contents[1]['href']
		
		#print("------------------------------------------------")
		#print("Title: %s" % hh[0].contents[1].string)
		#print("Link : %s" % hh[0].contents[1]['href'])
		hh = rows.findAll("p" , {"class": "size"})
		#print("Size : %s" % hh[0].contents[0].string)
		entry.size = hh[0].contents[0].string
		
		hh = rows.findAll("span" , { "class" : "s" } )		
		#print("Seed : %s" % hh[0].contents[0].string)
		entry.seeds = hh[0].contents[0].string
		
		List.addItem(entry)
		
		i += 1
	
	#List.printAllItems()
	
	return List
	
	

#///////////////////////////////////////////////////////////////////////////////
### OPENSHARING PARSER
def ParserOpenSharing():
	
	List = EntryList()
	
	h = httplib2.Http()
	response, content = h.request(('http://opensharing.org/c.php?search=call&make_search=1&method=0').replace(' ', '+'))
	html_file = content
    
	count = 0

	soup = BeautifulSoup(html_file.replace("</scr'+'ipt>", "</script>"))
	count = int(len(soup.findAll("tr")))

	i=5
	
	while i < count:
		
		entry = Entry()
		
		rows = soup.findAll("tr")[i]
		cols = rows.findAll("td")
		
		#print("------------------------------------------")
		#print("Title: %s" % PrepareTitle(cols[1].contents[4].contents))
		entry.title = PrepareTitle(cols[1].contents[4].contents)
		#print("Link : %s" % cols[1].contents[2]['href'])
		entry.link = cols[1].contents[2]['href']
		#print("Size : %s" % cols[int(len(cols))-1].string)
		entry.size  = cols[int(len(cols))-1].string
		
		cols = rows.findAll("span", {"class": "green"})
		#print("Seed : %s" % cols[0].contents[1].string)
		entry.seeds = cols[0].contents[1].string
		
		List.addItem(entry)
				
		i += 1
		
	return List

#////////////////////////////////////////////////////////////
### RUTOR PARSER
def ParserRutor():
	
	List = EntryList()
	
	h = httplib2.Http()
	response, content = h.request(('http://rutor.org/search/call').replace(' ', '+'))
	html_file = content
    
	count = 0
	
	soup = BeautifulSoup(html_file)
	count = int(len(soup.findAll("tr", { "class" : "gai" })))
    
	i = 0
    
	while i < count:
		rows = soup.findAll("tr", { "class" : "gai" })[i]
		seed = rows.findAll("span", {"class" : "green"})
		
		entry = Entry()
		entry.seeds = seed[0].contents[1]
		
		#print("Seeds: %s" % seed[0].contents[1])
		cols = rows.findAll("td")
					
		#print("Date: %s" % cols[0].string)
		
		entry.link = 'http://rutor.org' + cols[1].contents[0]['href']
			
		#print("Link: %s" % 'http://rutor.org' + cols[1].contents[0]['href'])
		
		entry.title = cols[1].contents[3].string
		
		#print("Title: %s" % cols[1].contents[3].string)
		
		
		if cols[3].string == None:
			#print("NONE FOUNDED!!!!!!!")
			entry.size = cols[2].string
			#print("Size: %s" % cols[2].string)
		else:
			entry.size = cols[3].string
			#print("Size: %s" % cols[3].string)
		
		#print("---------------------------------------------")
				
		List.addItem(entry)
		
		i+=1
		
	#List.printAllItems()
	
	return List

if __name__ == '__main__':
	
	print("Parser Tester")
	
	#tester = Tester("rutor")
	#tester = Tester("torrentino")
	#tester = Tester("opensharing")
	#tester.DataTest()
	
	for i in range(1,4):
		tester = Tester(i)
		tester.DataTest()
	
	#ParserOpenSharing()	
	#ParserRutor()
	#ParserTorrentino()

